// index.js
import api from '../../http/api/indexApi'
const Wxml2Canvas = require('wxml2canvas')
// 获取应用实例
const app = getApp()

Page({
  data: {
    width: 375,
    height: 690,
    canvasWidth: 0,
    canvasHeight: 0,
    imgs: '',
    interval: 5000,
    duration: 500,
    background: ['https://img2.baidu.com/it/u=1033146370,206787956&fm=253&fmt=auto&app=138&f=JPEG', 'https://img2.baidu.com/it/u=1033146370,206787956&fm=253&fmt=auto&app=138&f=JPEG', 'https://img2.baidu.com/it/u=1033146370,206787956&fm=253&fmt=auto&app=138&f=JPEG'],
    active: 0,
    show: false,
    actions: [{
        name: '选项',
      },
      {
        name: '选项',
      },
      {
        name: '选项',
        subname: '描述信息',
        openType: 'share',
      },
    ],
  },
  onClose() {
    this.setData({
      show: false
    });
  },

  onSelect(event) {
    console.log(event.detail);
  },
  draw() {
    uni.showLoading({
      title: "加载中...",
      mask: true
    })
    //创建wxml2canvas对象
    let drawImage = new Wxml2Canvas({
      element: 'canvas-map', // canvas节点的id,
      obj: this, // 在组件中使用时，需要传入当前组件的this
      width: this.width * 2, // 宽高
      height: this.height * 2,
      background: '#fff', // 默认背景色
      progress(percent) { // 绘制进度
      },
      finish(url) {
        // 画完后返回url
        console.log(url);
        setTimeout(() => {
          uni.previewImage({
            urls: [url]
          })
          uni.hideLoading()
        }, 300)
      },
      error(res) {
        console.log(res);
        uni.hideLoading()
        // 画失败的原因
      }
    });
    let data = {
      //直接获取wxml数据
      list: [{
        type: 'wxml',
        class: '.long_friend  .draw_canvas',
        limit: '.long_friend ',
        x: 0,
        y: 0
      }]
    }
    //传入数据，画制canvas图片
    drawImage.draw(data, this);
  },
  //动态获取画制作元素的宽高
  drawCanvas: function () {
    let that = this;
    const query = uni.createSelectorQuery().in(this);
    query.select('#long_friend').fields({
      size: true,
      scrollOffset: true
    }, data => {
      let width = data.width;
      let height = data.height;
      this.width = width;
      this.height = height;
    }).exec();
  },
  async generateCanvases() {
    wx.showLoading({
      title: '请稍候，该过程耗时较长...',
      mask: true
    })
    const that = this
    let base64List = []
    for (let i = 0; i < 9; i++) {
      let url = await that.startDraw(`travel${i+1}`, `.travel${i+1} .my_draw_canvas`)
      let base64 = await auth.downloadAndConvert(url)
      base64List.push(base64)
    }
    if (base64List.length === 9) {
      //查看图片
      wx.previewImage({
        urls: base64List,
      })
    }
  },
  startDraw(containerName, drawClass) {
    console.log(containerName);
    let that = this
    return new Promise((resolve, reject) => {
      const query = wx.createSelectorQuery().in(that);
      query.select(`#${containerName}`).fields({
        size: true,
        scrollOffset: true
      }, data => {
        console.log(data);
        const width = data.width;
        const height = data.height;
        that.setData({
          canvasWidth: width,
          canvasHeight: height
        })
        const drawMyImage = new Wxml2Canvas.default({
          element: 'myCanvas',
          obj: that,
          width: that.data.canvasWidth * 2,
          height: that.data.canvasHeight * 2,
          background: '#fff',
          finish: url => {
            resolve(url)
          },
          error: res => {
            wx.hideLoading();
          }
        });
        drawMyImage.draw({
          list: [{
            type: 'wxml',
            class: drawClass,
            limit: `.${containerName}`,
            x: 0,
            y: 0
          }]
        }, that);
      }).exec();
    });
  },
  drawImage1() {
    let self = this;
    this.drawImage1 = new Wxml2Canvas.default({
      width: 340, // 宽， 以iphone6为基准，传具体数值，其他机型自动适配
      height: 210, // 高
      element: 'canvas1',
      background: '#f0f0f0',
      progress(percent) {},
      finish(url) {
        let imgs = self.data.imgs;
        imgs.push(url);

        self.setData({
          imgs
        })
      },
      error(res) {}
    });

    let data = {
      list: [{
        type: 'wxml',
        class: '.share__canvas1 .draw_canvas', // draw_canvas指定待绘制的元素
        limit: '.share__canvas1', // 限定绘制元素的范围，取指定元素与它的相对位置
        x: 0,
        y: 0
      }]
    }

    this.drawImage1.draw(data);
  },

  onChange(event) {
    console.log(event);
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad() {
    api.getBannerApi({
      keywords: '海阔天空'
    }).then(res => {
      console.log(res);
    })
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },
  locationChose() {
    this.setData({
      show: true
    });
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})